package demo04;

import Utils.DataSourceUtils;
import demo04.Handler.BeanHandler;
import demo04.Handler.BeanListHandler;
import demo04.Handler.ScalarHandler;
import demo04.domain.Student;
import org.junit.Test;

import java.util.List;

public class JDBCTemplateTest {
    //创建jdbcTemplate对象
    JDBCTemplate template = new JDBCTemplate(DataSourceUtils.getDataSource());

    @Test
    public void selectScalar() {
        //查询student表的记录数
        String sql = "SELECT COUNT(*) FROM student";
        Long count = template.queryForScalar(sql, new ScalarHandler<Long>());
        System.out.println(count);
    }

    @Test
    public void selectAll() {
//查询所有学生信息
        String sql = "SELECT * FROM student";
        List<Student> list = template.queryForList(sql, new
                BeanListHandler<Student>(Student.class));
        for (Student stu : list) {
            System.out.println(stu);
        }
    }

    @Test
    public void selectOne() {
//查询张三这条记录
        String sql = "SELECT * FROM student WHERE sid=?";
//通过BeanHandler将结果封装成一个Student对象
        Student stu = template.queryForObject(sql, new BeanHandler<Student>
                (Student.class), 1);
        System.out.println(stu);
    }

    @Test
    public void delete() {
//删除周七这条记录
        String sql = "DELETE FROM student WHERE sid=?";
        int result = template.update(sql, 5);
        System.out.println(result);
    }

    @Test
    public void update() {
//修改张三的年龄为33
        String sql = "UPDATE student SET age=? WHERE name=?";
        Object[] params = {33, "张三"};
        int result = template.update(sql, params);
        System.out.println(result);
    }


}
